﻿using System;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace CardsSimulator
{
    class Client : MessageTransmitter
    {
        private Socket ServerSocket = null;
        public byte[] m_byBuff = new byte[655000];

        public Client()
        {
            ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            try
            {
                ServerSocket.Connect("127.0.0.1", 1024);

                var netStream = new NetworkStream(ServerSocket, true);
                var bf = new BinaryFormatter();
                var json = (String)bf.Deserialize(netStream);

                CardGame.currentGame = JsonConvert.DeserializeObject<CardGame>(json);

                CardGame.currentGame.Players.ElementAt(CardGame.currentGame.currentPlayerId).Transmitter = this;
                MessageBox.Show(text: CardGame.currentGame.currentPlayerId.ToString(), caption: "Sukces");
                
                var recieveData = new AsyncCallback(OnRecieve);
                ServerSocket.BeginReceive(m_byBuff, m_byBuff.Length, 0, SocketFlags.None, recieveData,ServerSocket);
            }
            catch (SocketException e)
            {
                MessageBox.Show(text: "Nie udało się połączyć z serwerem", caption: "Błąd");
            }
            
        }

        private void OnRecieve(IAsyncResult ar)
        {
            var socket = (Socket)ar.AsyncState;
            socket.EndReceive(ar);
            var stream = new NetworkStream(socket);
            var bf = new BinaryFormatter();
            stream.Flush();
            var json = (String)bf.Deserialize(stream);

            GameState move = JsonConvert.DeserializeObject<GameState>(json);
            CardGame.currentGame.AcceptMove(move);
            
            socket.BeginReceive(m_byBuff, m_byBuff.Length, 0, SocketFlags.None, new AsyncCallback(OnRecieve), socket);
        }

        public void SendMessage(GameState move)
        {
            var json = JsonConvert.SerializeObject(move);

            var netStream = new NetworkStream(ServerSocket, true);
            var bf = new BinaryFormatter();
            var ms = new MemoryStream();
            bf.Serialize(ms, json);
            netStream.Write(ms.ToArray(), 0, ms.ToArray().Length);
        }
    }
}
